//
//  BaseModel.m
//  EFHealth
//
//  Created by nf on 17/2/20.
//  Copyright © 2019年 ef. All rights reserved.
//

#import "BaseModel.h"

typedef  void (^SuccessBlock)(NSURLSessionDataTask * _Nonnull, id _Nullable);
typedef  void (^FailureBlock)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull);
typedef void (^ProgressBlock)(NSProgress * _Nonnull);
@interface BaseModel()
{
    NSURLSessionDataTask *_operation ;
}

@property (nonatomic,weak)id<BaseModelProtocol> Delegate ;
@property (nonatomic,assign)BOOL needCache ;

@end

@implementation BaseModel

- (instancetype)initWithDelegate:(id<BaseModelProtocol>)Delegate cache:(BOOL)cache
{
    if (self = [super init]) {
        self.Delegate = Delegate ;
        self.needCache = cache ;
    }
    return self ;
}
//url中公共参数<user中用>
- (NSDictionary *)commonParameters
{
    NSMutableDictionary *commP = [NSMutableDictionary dictionaryWithCapacity:2];
    [commP setValue:EFVersionTag forKey:@"version"];
    [commP setValue:@"ios" forKey:@"platform"];
    return commP;
}

//全局单例 数据下载接口头部<user不需要cookie参数，所以user接口不需要它>
- (EFApiClient *)getClient
{
    EFApiClient* client = [EFApiClient sharedMClient];
    EFAppContext *appContext = [EFAppContext sharedContext];
    [client.requestSerializer setValue:@"androiduser" forHTTPHeaderField:@"idfv"];
//    [client.requestSerializer setValue:appContext.unitId forHTTPHeaderField:@"unitId"];
    [client.requestSerializer setValue:EUInitId forHTTPHeaderField:@"unitId"];
    if(!ISEMPTY(appContext.authorization)){
        [client.requestSerializer setValue:appContext.authorization forHTTPHeaderField:@"authorization"];
    }else{
        [client.requestSerializer setValue:@"9533" forHTTPHeaderField:@"authorization"];
    }
    return client;
}
- (void)cancelRequest
{
    if (_operation.state != NSURLSessionTaskStateCanceling) {
        [_operation cancel];
    }
}
- (void)cancelAllRequest
{
    [[EFApiClient sharedMClient].operationQueue cancelAllOperations];
}
- (SuccessBlock)getSuccessBlock:(id)weakSelf
{
    return ^(NSURLSessionDataTask * _Nonnull request, id _Nullable response){
#warning ====new model response data=======
        __weak __typeof(self) weakSelf = self;
        queueMainStart
        if ([response isKindOfClass:[NSDictionary class]]) {
            NSDictionary* responseDict = [NSDictionary dictionaryWithDictionary:(NSDictionary*)response];
            //将responseDict中所有的NSNull类型替换成@""
            responseDict = [NSDictionary changeType:responseDict];
            NSLog(@"responseDict = %@",responseDict);
            NSError* error = nil;
            BaseResponse* responseModel = nil;
            @try {
                responseModel = [[[_parseModelClass class] alloc] initWithDictionary:responseDict error:&error];
                
            }@catch (NSException *exception) {
                EFLog(@"数据解析出错 error:%@ == %@  ==== %@", weakSelf,exception,error);
            }
            
            if (nil == responseModel || error) {
                responseModel = [[BaseResponse alloc]initWithDictionary:responseDict error:&error];
            }
            
            if (responseModel.resCode == 200 && nil == error && nil != responseModel) {//数据正常
                //通知代理处理数据
                if (self.Delegate && [self.Delegate respondsToSelector:@selector(getDataFinish:netResponse:)]) {
                    [self.Delegate getDataFinish:weakSelf netResponse:responseModel];
                }
            }
            else{
                
//                if (responseModel.resCode == 2001) {//密码错误
//                    error = [NSError errorWithDomain:responseModel.message code:apiErrorCodePsdError userInfo:nil];
//                }
                if(responseModel.resCode == 445){//登录失效
                    error = [NSError errorWithDomain:responseModel.message code:apiErrorCodeNoLogin userInfo:nil];
                }
//               else if (responseModel.resCode != 0) {//说明后台处理了错误信息
//
//                    if (ISEMPTY(responseModel.message)) {
//                        responseModel.message = @"后台错误";
//                    }
//                    error = [NSError errorWithDomain:responseModel.message code:apiErrorCodeResultError userInfo:nil];
//                }
//                else{
//                    error = [NSError errorWithDomain:@"解析错误" code:apiErrorCodePrasultError userInfo:nil];
//                }
                else{
                    error = [NSError errorWithDomain:responseModel.message code:apiErrorCodePrasultError userInfo:nil];
                }
                if (self.Delegate && [self.Delegate respondsToSelector:@selector(getDataFinish:netError:)]) {
                    [self.Delegate getDataFinish:weakSelf netError:error];
                }
                
            }
        }
        else{
            
            NSError *error = [NSError errorWithDomain:@"数据错误(-1024)" code:apiErrorCodeNoDictionary userInfo:nil];
            if (self.Delegate && [_Delegate respondsToSelector:@selector(getDataFinish:netError:)]) {
                [self.Delegate getDataFinish:weakSelf netError:error];
            }
        }
        queueEnd
        
    };
}
- (FailureBlock)getFailureBlock:(id)weakSelf
{
    return ^(NSURLSessionDataTask * _Nullable request, NSError * _Nonnull error){
        
        queueMainStart
        if (request.state != NSURLSessionTaskStateCanceling) {//这是网络错误
            
            NSMutableString *errorStr = [NSMutableString stringWithString:@"网络错误"];
            if(request.response){
                NSInteger responseCode = ((NSHTTPURLResponse *)request.response).statusCode ;
                if (DEBUG_Development) {
                    [errorStr appendFormat:@"(%d_%d)",error.code,((NSHTTPURLResponse *)request.response).statusCode ];//3840 404  -1001请求超时 -1003未能找到使用指定主机名的服务器 -1009 似乎已断开与互联网的连接
                }
                else{
                    [errorStr appendFormat:@"(%d)",responseCode==0 ? error.code : responseCode];
                }
            }
            NSError *errorN = [NSError errorWithDomain:errorStr code:apiErrorCodeNetNo userInfo:nil];
           
            if (self.Delegate && [_Delegate respondsToSelector:@selector(getDataFinish:netError:)]) {
                [self.Delegate getDataFinish:weakSelf netError:errorN];
            }
            EFLog(@"网络错误：%@",error);
        }
        else{//这是取消请求
            
            EFLog(@"==========取消请求===== %@",request);
        }
        queueEnd
    };
}
- (ProgressBlock)getProgressBlock:(id)weakSelf
{
    return ^(NSProgress * _Nonnull downloadProgress){
        EFLog(@"下载进度%@ %d = %d \n\n\n",weakSelf,downloadProgress.totalUnitCount , downloadProgress.completedUnitCount);
    };
}

- (void)upLoadImage:(UIImage *)image scale:(float)scale
{
    NSData *imgData = UIImageJPEGRepresentation(image, scale);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    __weak __typeof(self) weakSelf = self;
    [manager POST:api_upLoadImage parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imgData name:@"userfile123" fileName:@"userfile123.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        TFHpple *hpple=[[TFHpple alloc] initWithHTMLData:responseObject];
//        NSArray * elements  = [hpple searchWithXPathQuery:@"//h1"];
//        TFHppleElement * element = [elements objectAtIndex:0];
//        NSString *MD5Photo=[element.text substringFromIndex:[element.text rangeOfString:@"MD5: "].length];
//        NSString *imgURL = [NSString stringWithFormat:@"http://mbank.nf1000.com/simg/%@",MD5Photo] ;
//        
//        if (_Delegate && [_Delegate respondsToSelector:@selector(getUpLoadImageSuccess:)]) {
//            
//            [_Delegate getUpLoadImageSuccess:imgURL];
//        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (_Delegate && [_Delegate respondsToSelector:@selector(getDataFinish:netError:)]) {
            [_Delegate getDataFinish:weakSelf netError:error];
        }
    }];
}
- (void)getPath:(NSString *)path parameters:(NSDictionary *)parameters
{
    EFApiClient *client = [self getClient];
    
    _parameterDict = parameters ;
    __weak __typeof(self) weakSelf = self;
    _operation = [client GET:path parameters:parameters
                    progress:[self getProgressBlock:weakSelf]
                     success:[self getSuccessBlock:weakSelf]
                     failure:[self getFailureBlock:weakSelf]];
}

//- (void)postPath:(NSString *)path parameters:(NSDictionary *)parameters
//{
//    EFApiClient *client = [self getClient];
//
//    _parameterDict = parameters ;
//    __weak __typeof(self) weakSelf = self;
//    _operation = [client POST:path  parameters:parameters
//                     progress:[self getProgressBlock:weakSelf]
//                      success:[self getSuccessBlock:weakSelf]
//                      failure:[self getFailureBlock:weakSelf]];
//}
- (void)postPath:(NSString *)path parameters:(NSDictionary *)parameters{
    
    // 1.创建请求
    NSString *urlString = [NSString stringWithFormat:@"%@%@",EFBaseURL,path];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
    request.HTTPMethod = @"POST";
   
    // 2.设置请求类型
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"androiduser" forHTTPHeaderField:@"idfv"];
    [request setValue:EUInitId forHTTPHeaderField:@"unitId"];
    EFAppContext *appContext = [EFAppContext sharedContext];
//    [request setValue:appContext.unitId forHTTPHeaderField:@"unitId"];
    if(!ISEMPTY(appContext.authorization)){
        [request setValue:appContext.authorization forHTTPHeaderField:@"authorization"];
    }else{
        [request setValue:@"9533" forHTTPHeaderField:@"authorization"];
    }
    request.HTTPBody = data;
  
   // 3.发送请求
   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
       if(!data) return;
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
       __weak __typeof(self) weakSelf = self;
       //将responseDict中所有的NSNull类型替换成@""
       responseDict = [NSDictionary changeType:responseDict];
       NSLog(@"responseDict = %@",responseDict);
       NSError* error = nil;
       BaseResponse* responseModel = nil;
       @try {
           responseModel = [[[_parseModelClass class] alloc] initWithDictionary:responseDict error:&error];
           
       }@catch (NSException *exception) {
           EFLog(@"数据解析出错 error:%@ == %@  ==== %@", weakSelf,exception,error);
       }
       
       if (nil == responseModel || error) {
           responseModel = [[BaseResponse alloc]initWithDictionary:responseDict error:&error];
       }
       
       if(responseModel != nil){
           if (responseModel.resCode == 200 && nil == error && nil != responseModel) {//数据正常
               if (self.Delegate && [self.Delegate respondsToSelector:@selector(getDataFinish:netResponse:)]) {
                   [self.Delegate getDataFinish:weakSelf netResponse:responseModel];
               }
           }else{
               if(ISEqual(path, @"xqn/app/member/edit")){
                   //编辑个人信息成功，后台返回的resCode == 5？？？
                   if (responseModel.resCode == 5) {
                       if (self.Delegate && [self.Delegate respondsToSelector:@selector(getDataFinish:netResponse:)]) {
                           [self.Delegate getDataFinish:weakSelf netResponse:responseModel];
                       }
                   }else{
                       error = [NSError errorWithDomain:responseModel.message code:apiErrorCodePrasultError userInfo:nil];
                       [self.Delegate getDataFinish:weakSelf netError:error];
                   }
               }else{
                   error = [NSError errorWithDomain:responseModel.message code:apiErrorCodePrasultError userInfo:nil];
                   [self.Delegate getDataFinish:weakSelf netError:error];
               }
           }
       }
   }];
}


@end

















